package com.zeny.express.framework.mq.activemq;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zeny.express.framework.mq.AbstractMqPool;
import com.zeny.express.framework.mq.MqCallback;
import com.zeny.express.framework.shared.exception.ApplicationException;

public class ActiveMqTemplate {
	protected final static Logger LOGGER = LoggerFactory
			.getLogger(ActiveMqTemplate.class);
	
	@SuppressWarnings("deprecation")
	public <T> T execute(AbstractMqPool mqPool, MqCallback<T, ActiveMqQueueHandler> action) {
		ActiveMqQueueHandler handler = null;
		boolean success = false;

		try {
			handler = (ActiveMqQueueHandler)mqPool.getResource();
			
			T result = action.doInMq(handler);

			success = true;

			return result;
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			throw new ApplicationException(ApplicationException.UNKNOWN, null);
		} finally {
			if (handler != null) {
				try {
					if (success) {
						handler.commit();
						
						mqPool.returnResource(handler);
					} else {
						handler.rollback();
						
						mqPool.returnBrokenResource(handler);
					}
				} catch (Exception e) {
					mqPool.returnBrokenResource(handler);
					
					LOGGER.error(e.getMessage(), e);
					throw new ApplicationException(
							ApplicationException.UNKNOWN, null);
				}
			}
		}

	}
}
